package a51qindian.com.comprehensive.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.li.interfaces.OnItemClickListener;
import com.li.utils.ToastUtil;
import com.li.widget.MultipleLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import a51qindian.com.comprehensive.Const;
import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.adapter.AdvVerifyAdapter;
import a51qindian.com.comprehensive.base.QDBaseFragment;
import a51qindian.com.comprehensive.items.LinearItemDecoration;
import a51qindian.com.comprehensive.model.AdvInfo;
import a51qindian.com.comprehensive.model.BaseModel;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import a51qindian.com.comprehensive.net.SelectorObserver;
import a51qindian.com.comprehensive.util.SpUtil;
import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Author: Li
 * Date: 2017/9/22 0022
 * Description: 城市  置顶广告审核
 */

public class AdvVerifyFragment extends QDBaseFragment {
    @BindView(R.id.recycler_adv)
    RecyclerView mRecyclerAdv;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;
    @BindView(R.id.layout_refresh)
    SmartRefreshLayout mLayoutRefresh;


    public static final String ADV_VERIFY_TYPE = "type";
    public static final String ADV_VERIFY_FINISHED = "1";
    public static final String ADV_VERIFY_UNFINISHED = "0";

    private static final String ADV_PASS = "1";
    private static final String ADV_REFUSED = "2";

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_adv_verify;
    }

    private String mType;
    private List<AdvInfo> mAdvInfoList;
    //审核弹出界面
    private AlertDialog.Builder mBuilder;
    private AdvVerifyAdapter mAdapter;

    public static AdvVerifyFragment newInstance(String type) {
        Bundle args = new Bundle();
        args.putString(ADV_VERIFY_TYPE, type);
        AdvVerifyFragment fragment = new AdvVerifyFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initSth() {
        super.initSth();
        mAdvInfoList = new ArrayList<>();
        mType = getArguments().getString(ADV_VERIFY_TYPE, "");
        mRecyclerAdv.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerAdv.addItemDecoration(new LinearItemDecoration());
        mAdapter = new AdvVerifyAdapter(mContext, mType);
        mRecyclerAdv.setAdapter(mAdapter);
        mAdapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int pos) {
                showVerifyDialog("提示", "广告审核", pos);
            }
        });
        setSmartRefreshLayout(mLayoutRefresh);
    }


    /**
     * 显示广告审核对话框
     *
     * @param title 标题
     * @param msg   消息
     * @param pos   位置，用于更新界面
     */
    private void showVerifyDialog(String title, String msg, final int pos) {
        if (mBuilder == null) {
            mBuilder = new AlertDialog.Builder(mContext)
                    .setTitle(title)
                    .setMessage(msg)
                    .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            verifyAdv(mUid, mAdvInfoList.get(pos).getAid(), ADV_REFUSED, pos);
                        }
                    })
                    .setPositiveButton("通过", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            verifyAdv(mUid, mAdvInfoList.get(pos).getAid(), ADV_PASS, pos);
                        }
                    });
        } else {
            mBuilder.setTitle(title)
                    .setMessage(msg);
        }
        mBuilder.create().show();
    }

    /**
     * 广告审核处理
     *
     * @param uid    用户编号
     * @param aid    广告编号
     * @param status 审核状态 1：通过  2：拒绝
     * @param pos    位置  ：更新界面
     */
    private void verifyAdv(String uid, String aid, String status, final int pos) {
        mLayoutContent.onLoadingWithContent();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("aid", aid);
        map.put("status", status);
        ObservableHelper.createObservable(RetrofitCreator.createService().advVerify(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject object = new JSONObject(s);
                            showToast(object.getString("info"));
                            if (object.getInt("code") == 1) {
                                mAdvInfoList.remove(pos);
                                mAdapter.notifyItemRemoved(pos);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        super.onLoadmore(refreshlayout);
        showAdvVerify(mUid, mType, String.valueOf(mPage + 1));
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        super.onRefresh(refreshlayout);
        showAdvVerify(mUid, mType, "0");
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        if (mType.equals(ADV_VERIFY_UNFINISHED)) {
            showAdvVerify(SpUtil.getUserInfo(mContext, SpUtil.USER_ID), mType, "0");
        }
    }

    @Override
    protected void onFirstVisible() {
        super.onFirstVisible();
        if (mType.equals(ADV_VERIFY_FINISHED)) {
            showAdvVerify(SpUtil.getUserInfo(mContext, SpUtil.USER_ID), mType, "0");
        }
    }


    private void showAdvVerify(String uid, String type, String page) {
        mLayoutContent.onLoadingWithContent();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("status", type);
        map.put("page", page);
        ObservableHelper.createObservable(RetrofitCreator.createService().advList(map))
                .subscribe(new SelectorObserver<BaseModel<List<AdvInfo>>>() {
                    @Override
                    protected void onErrorCodeInfo(int code, String info) {
                        mLayoutContent.onSuccess();
                        stopRefreshLoad();
                        mLayoutRefresh.setLoadmoreFinished(true);
                        ToastUtil.showToast(mContext, info);
                    }

                    @Override
                    protected void onSuccess(BaseModel<List<AdvInfo>> listBaseModel) {

                        List<AdvInfo> advInfoList = listBaseModel.getData();
                        mLayoutContent.onSuccess();
                        if (mIsRefresh) {
                            mPage = 0;
                            mAdvInfoList.clear();
                            mLayoutRefresh.setLoadmoreFinished(false);
                        } else {
                            mPage++;
                        }
                        stopRefreshLoad();
                        if (!mIsRefresh && advInfoList.size() < Const.DEFAULT_PAGE_SIZE) {
                            mLayoutRefresh.setLoadmoreFinished(true);
                        }
                        mAdvInfoList.addAll(advInfoList);
                        mAdapter.setAdvInfoList(mAdvInfoList);
                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        stopRefreshLoad();
                    }
                });


    }
}
